<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <h1>The Ajax 02 Page</h1>
        <button onclick="doAjaxGet()">DO Ajax Get</button>
        <button onclick="doAjaxPost()">DO Ajax Post</button>
        <button onclick="doAjaxDelete()">DO Ajax Delete</button>
        <button onclick="doAjaxPut()">DO Ajax Put</button>
    </div>
    <div id="result">

    </div>
    <script>
        function doAjaxPut(){
            //1.创建XHR对象
            let xhr=new XMLHttpRequest();
            //2.设置状态监听
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4){
                    if(xhr.status==200){
                        let div=document.getElementById("result");
                        div.innerHTML=xhr.responseText;
                    }
                }
            }
            //3.建立连接
            let params="id=101&city=tianjin"
            xhr.open("put",`http://localhost/doAjaxPut`,true);
            //put请求必须要设置请求头
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            //4.发送请求
            xhr.send(params);//put请求可以将参数放到send方法内部
        }
        function doAjaxDelete(){
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function (){
                if(xhr.readyState==4&&xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
            let param="102"
            xhr.open("delete",`http://localhost/doAjaxDelete/${param}`,true);
            xhr.send(null);
        }
        function doAjaxPost(){
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function (){
                if(xhr.readyState==4&&xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
            let params="id=102&city=shenzhen"
            xhr.open("post",`http://localhost/doAjaxPost/`,true);
            //post请求必须要设置请求头
            //请求头设置了json格式接收数据
            //xhr.setRequestHeader("Content-type","application/json",)
            //请求头表单格式接收数据
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded",)
            xhr.send(params);
        }
        function doAjaxGet(){
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function (){
                if(xhr.readyState==4&&xhr.status==200){
                    document.getElementById("result").innerHTML=xhr.responseText;
                }
            }
            let param=""
            xhr.open("GET",`http://localhost/doAjaxGet/${param}`,true);
            xhr.send(null);
        }
    </script>
</body>
</html>